package com.seley.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.seley.config.WebSecurityConfig;

@Controller
public class TestController {
	
	@Value("${system.title}")
	private String title;

	@Value("${system.loginUser}")
	private String loginUser;

	@Value("${system.loginPwd}")
	private String loginPwd;
	
	@GetMapping("/")
	public String index() {
		return "index";
	}
	
	@PostMapping("/login")
	@ResponseBody
	public Map<String, Object> loginPost(@RequestParam("username") String username,
			@RequestParam("password") String password, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (!loginUser.equals(username)) {
			map.put("success", false);
			map.put("message", "用户名错误");
			return map;
		}
		
		if (!loginPwd.equals(password)) {
			map.put("success", false);
			map.put("message", "密码错误");
			return map;
		}
		
		// 设置session
		session.setAttribute(WebSecurityConfig.SESSION_KEY, username);

		map.put("success", true);
		map.put("message", "登录成功");
		return map;
	}
	
	@GetMapping("/home")
	public String home(Model model) {
		//标题
		model.addAttribute("title", title);
		
		//用户信息
		Map<String, Object> user = new HashMap<String, Object>();
		user.put("name", loginUser);
		user.put("role", "管理员");
		model.addAttribute("user", user);
		
		//一些数据集合
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		
		Map<String, Object> data1 = new HashMap<String, Object>();
		data1.put("dqn", "beijing");
		data1.put("dqt", "北京");
		
		Map<String, Object> data2 = new HashMap<String, Object>();
		data2.put("dqn", "shanghai");
		data2.put("dqt", "上海");
		
		list.add(data1);
		list.add(data2);
		
		model.addAttribute("dataList", list);
		
		return "home";
	}
}
